package com.googlecode.spruce.web.admin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.spruce.dao.ServiceDao;
import com.googlecode.spruce.dao.ServiceGroupDao;
import com.googlecode.spruce.domain.Service;
import com.googlecode.spruce.domain.ServiceGroup;

@Controller
@RequestMapping("/admin/service")
public class ServiceDashboard
{

    @Autowired
    private ServiceDao serviceDao;

    @Autowired
    private ServiceGroupDao serviceGroupDao;

    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public ModelAndView getAll()
    {
        final ModelAndView model = new ModelAndView("service/index");

        final List<Service> services = this.serviceDao.getAll();
        final List<ServiceGroup> serviceGroups = this.serviceGroupDao.getAll();

        model.addObject("services", services);
        model.addObject("serviceGroups", serviceGroups);

        return model;
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public ModelAndView add(@RequestParam("pluginName") String pluginName, @RequestParam("sgid") Integer serviceGroupID)
    {
        final ServiceGroup serviceGroup = this.serviceGroupDao.findByID(serviceGroupID);

        final Service service = new Service();

        service.setPluginName(pluginName);
        service.setServiceGroup(serviceGroup);

        this.serviceDao.save(service);

        return getAll();
    }

    @RequestMapping(value = "/delete.do", method = RequestMethod.GET)
    public ModelAndView delete(@RequestParam("serviceid") Integer id)
    {
        this.serviceDao.delete(this.serviceDao.findByID(id));

        return getAll();
    }
}
